package Tools;

public class Histogram {
	long hist[];
	long binSize;
	long numEntries;
	
	public Histogram(long maxValue, long binSize){
		hist=new long[(int)(maxValue/binSize)+1];
		this.binSize=binSize;
		this.numEntries=0;
	}
	
	public Histogram(long hist[],long binSize,long numEntries){
		this.hist=hist;
		this.binSize=binSize;
		this.numEntries=numEntries;
	}
	
	public Histogram(Histogram old){
		this.hist=old.hist;
		this.binSize=old.binSize;
		this.numEntries=old.numEntries;
	}
	
	public void add(long num){
		int bin=(int)(num/binSize);
		if (bin>=hist.length)
			bin=hist.length-1;
		hist[bin]+=1;
		numEntries++;
	}
	
	/**
	 * Returns the nth percentile histogram value
	 * @param percentile - n in decimal form (eg. 90th percentile = 0.9)
	 */
	public long getPercentile(double percentile){
		long valuesChecked=0;
		int bin=0;
		while(valuesChecked<(percentile*(double)numEntries)){
			valuesChecked+=hist[bin];
			bin++;
		}
		return (bin+1)*this.binSize;
	}
	
	public void clear(){
		numEntries=0;
		for (int i=0;i<hist.length;i++)
			hist[i]=0;
	}
	
	public Histogram clone(){
		return new Histogram(this.hist,this.binSize,this.numEntries);
	}

}
